package com.rabbiter.hwm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbiter.hwm.controller.dto.StudentDTO;
import com.rabbiter.hwm.entity.StudentFile;
import com.rabbiter.hwm.mapper.StudentFileMapper;
import com.rabbiter.hwm.service.IAutoCheckService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * 自动批改服务实现类
 */
@Service
public class AutoCheckServiceImpl implements IAutoCheckService {

    // 存储作业ID和关键词映射关系，实际项目中可以使用数据库存储
    private static final Map<Integer, String> answerKeywordsMap = new HashMap<>();

    @Resource
    private StudentFileMapper studentFileMapper;

    @Override
    public StudentDTO autoCheckHomework(StudentFile studentFile) {
        // 创建返回的DTO对象
        StudentDTO result = new StudentDTO(
                studentFile.getId(),
                studentFile.getStudent(),
                studentFile.getDwc(),
                studentFile.getUserFileId(),
                studentFile.getTitle(),
                studentFile.getAn1(),
                studentFile.getContent(),
                1, // 默认设置为通过状态
                0  // 默认分数为0
        );

        // 获取该作业的参考答案关键词
        String keywords = getAnswerKeywords(studentFile.getUserFileId());
        if (keywords == null || keywords.trim().isEmpty()) {
            // 如果没有设置关键词，则返回基础DTO
            return result;
        }

        // 计算分数
        int score = calculateScore(studentFile.getAn1(), keywords);
        result.setScore(score);

        // 根据分数设置状态
        if (score < 60) {
            result.setFlag(2); // 未通过
        } else {
            result.setFlag(1); // 通过
        }

        return result;
    }

    @Override
    public void setAnswerKeywords(Integer userFileId, String keywords) {
        answerKeywordsMap.put(userFileId, keywords);
    }

    @Override
    public String getAnswerKeywords(Integer userFileId) {
        return answerKeywordsMap.get(userFileId);
    }

    @Override
    public int batchAutoCheckHomework(Integer userFileId) {
        // 查询该作业下所有未批改的学生作业
        QueryWrapper<StudentFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_file_id", userFileId);
        queryWrapper.eq("flag", 0); // 未批改的作业

        List<StudentFile> studentFiles = studentFileMapper.selectList(queryWrapper);
        int checkedCount = 0;

        // 批量自动批改
        for (StudentFile studentFile : studentFiles) {
            StudentDTO result = autoCheckHomework(studentFile);
            studentFile.setFlag(result.getFlag());
            studentFile.setScore(result.getScore());
            studentFileMapper.updateById(studentFile);
            checkedCount++;
        }

        return checkedCount;
    }

    /**
     * 根据关键词计算作业分数
     * @param answer 学生答案
     * @param keywords 关键词字符串，格式为：关键词1:权重1,关键词2:权重2,...
     * @return 计算得出的分数
     */
    private int calculateScore(String answer, String keywords) {
        if (answer == null || answer.trim().isEmpty()) {
            return 0;
        }

        int totalScore = 0;
        StringTokenizer tokenizer = new StringTokenizer(keywords, ",");

        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            String[] parts = token.split(":");
            if (parts.length == 2) {
                String keyword = parts[0];
                try {
                    int weight = Integer.parseInt(parts[1]);
                    // 检查答案中是否包含关键词
                    if (answer.toLowerCase().contains(keyword.toLowerCase())) {
                        totalScore += weight;
                    }
                } catch (NumberFormatException e) {
                    // 忽略格式错误的权重
                }
            }
        }

        // 确保分数在0-100之间
        return Math.min(Math.max(totalScore, 0), 100);
    }
}